//
//  JYSportMainViewController.m
//  FinderBox
//
//  Created by JiYi on 2018/10/12.
//  Copyright © 2018 JiYi. All rights reserved.
//

#import "JYSportViewController.h"
#import "JYCircleProgress.h"
#import <CoreMotion/CoreMotion.h>

#import "JYSportPlanViewController.h"

#import "JYTimeCircle.h"
#import "CountDownView.h"

#define CALORIE_STEP 0.04 //每行走一步 预估消耗卡路里


@interface JYSportViewController ()

//  开始运动
@property (nonatomic, strong) UIButton * startBtn;
//  中间视图
@property (nonatomic, strong) UIView * centerView;
@property (nonatomic, strong) UIView * totalKm;
@property (nonatomic, strong) UIView * totalKLL;
@property (nonatomic, strong) UIView * totalPre;

//  具体文字
@property (nonatomic, strong) UILabel * kmValue;
@property (nonatomic, strong) UILabel * kmTips;
@property (nonatomic, strong) UILabel * kllValue;
@property (nonatomic, strong) UILabel * kllTips;
@property (nonatomic, strong) UILabel * preValue;
@property (nonatomic, strong) UILabel * preTips;

//  按钮
@property (nonatomic, strong) UIView * handleView;
@property (nonatomic, strong) UIButton * historyBtn;
@property (nonatomic, strong) UIButton * setPlanBtn;

//  顶部视图
@property (nonatomic,strong) JYCircleProgress * circleProgress;




@property (nonatomic,assign)BOOL playing;//是否启动运动
@property (nonatomic,assign)NSInteger thisMaxStep;//本次运动的预定步数
@property (nonatomic,strong)CMPedometer * pedometer;
@property (nonatomic,strong)StepModel * everyModel;//每日计划
@property (nonatomic,strong)StepModel * lastModel;//最后一条计划


//  中间的倒计时
@property (nonatomic, strong) JYTimeCircle * topCircleView;
@property (nonatomic, strong) CountDownView * trackView;
@property (nonatomic, strong) CountDownView * processView;
@property (nonatomic, strong) UIView * timeView;
@property (nonatomic, strong) UILabel * showTimeLabel;

@end

@implementation JYSportViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.hbd_barAlpha = 0.0f;
    self.hbd_barHidden = YES;
    
    self.hbd_titleTextAttributes = @{NSForegroundColorAttributeName:UIColor.whiteColor};
    self.hbd_tintColor = UIColor.whiteColor;
    
//    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:nil];

    self.navigationController.navigationItem.title = @"";
    
    [self.view addSubview:self.circleProgress];
    
    [self setupMainUI];
    
    [self addAction];
    
    //获取每日计划
    NSArray * allArray =[WHCSqlite query:[StepModel class] where:@"isEveryDay = 1" order:@"by createTime asc"];
    self.everyModel = allArray.lastObject;
    //获取最后一条计划
    NSArray * lastArray =[WHCSqlite query:[StepModel class] where:@"isEveryDay = 0" order:@"by createTime asc"];
    self.lastModel = lastArray.lastObject;
    __weak typeof(self) weakSelf = self;
    
    [[WQPermissionRequest createWQPermissionRequest] requestPermission:WQHealth title:@"小袋鼠需要访问您的健康权限" description:@"为了可以给您更好的体验，小袋鼠需要您的同意获取运动传感器数据" requestResult:^(BOOL granted, NSError *error) {
        if (granted) {
            [HealthKitManagerShareInstance authorizeHealthKit:^(BOOL success, NSError *error) {
                [weakSelf updateUI:0];
            }];
        }
    }];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReciveNotification:) name:@"didReciveNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finishSettingModel:) name:@"finishSettingModel" object:nil];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    __weak typeof(self) weakSelf = self;
    [[WQPermissionRequest createWQPermissionRequest] requestPermission:WQHealth title:@"小袋鼠需要访问您的健康权限" description:@"为了可以给您更好的体验，小袋鼠需要您的同意获取运动传感器数据" requestResult:^(BOOL granted, NSError *error) {
        if (granted) {
            [HealthKitManagerShareInstance authorizeHealthKit:^(BOOL success, NSError *error) {
                [weakSelf updateUI:0];
            }];
        }
    }];

}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)finishSettingModel:(NSNotification *)noti {
    //
    
    StepModel * model = noti.object;
    self.everyModel = model;
    [self updateUI:0];
}

#pragma mark - 事件处理
- (void)addAction {
    [_startBtn addTarget:self action:@selector(startBtnClick:) forControlEvents:UIControlEventTouchUpInside];
}
#pragma mark - 开始运动
- (void)startBtnClick:(UIButton *)button {
    __weak typeof(self) weakSelf = self;
    if (!button.selected) { //开始运动
        JYSportPlanViewController * sportPlan = [[UIStoryboard storyboardWithName:@"JYSportPlanViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"JYSportPlanViewController"];
        sportPlan.onceTag = YES;
        sportPlan.settingBlock = ^(BOOL success, StepModel *model) {
            if (success && model) {
                weakSelf.everyModel = model;
                [weakSelf updateUI:0];
                button.selected = !button.selected;
            }
        };
        sportPlan.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:sportPlan animated:YES];
    }else{//结束运动
        [weakSelf stop];
        [weakSelf updateUI:0];
        button.selected = !button.selected;
    }
}

#pragma mark - 通知处理
- (void)didReciveNotification:(NSNotification *)notif {
    NSString * identifer =  notif.userInfo[@"idf"];
    NSString * sql = [NSString stringWithFormat:@"identifer = '%@'",identifer];
    NSArray * array =[WHCSqlite query:[StepModel class] where:sql];
    for (StepModel * model in array) {
        if (!model.isEveryDay) {
            [UserNotificationManager removeNotificationWithIdentifer:model.identifer];
            [self stop];
            self.startBtn.selected = NO;
        }
    }
    [self updateUI:0];
}
- (void)updateUI:(NSNumber *)steps {
    __weak typeof(self) weakSelf = self;
    steps = steps?steps:[NSNumber numberWithInt:0];
    __block NSInteger maxStep;
    if (self.playing) {
        maxStep = weakSelf.lastModel.totalStep == 0?10000:weakSelf.lastModel.totalStep;
        weakSelf.circleProgress.progressLabel.text = [NSString stringWithFormat:@"%@",steps];
    }
    [self.pedometer queryPedometerDataFromDate:[[NSDate date] jk_zeroDate] toDate:[NSDate date]  withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
        NSNumber * stepNum = pedometerData.numberOfSteps;
        int stepCount = [stepNum intValue];
        if (!error) {
            [GCDQueue executeInMainQueue:^{
                if (!self.playing){
                    maxStep = weakSelf.everyModel.totalStep == 0?10000:weakSelf.everyModel.totalStep;
                    [weakSelf.circleProgress progressValue:stepCount maxValue:maxStep];
                }
                weakSelf.preValue.text = [NSString stringWithFormat:@"目标%ld步",(long)maxStep];
                weakSelf.showTimeLabel.text = [NSString stringWithFormat:@"%d",stepCount];
            }];
        }else{
            
        }
    }];
    
    
    
    
    [HealthKitManagerShareInstance getDistanceForToday:^(double distance, NSError *error) {
        [GCDQueue executeInMainQueue:^{
            weakSelf.kmValue.text = [NSString stringWithFormat:@"%.2fkm", distance];
        }];
    }];
}


- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

- (void)start{
    if(![CMPedometer isStepCountingAvailable]){
        return;
    }
    self.playing = YES;
    [self.pedometer startPedometerUpdatesFromDate:[NSDate date] withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
        [self performSelectorOnMainThread:@selector(updateUI:) withObject:pedometerData.numberOfSteps waitUntilDone:YES];
    }];
    
}
- (void)stop{
    [self.pedometer stopPedometerUpdates];
    self.playing = NO;
}

- (CMPedometer *)pedometer{
    if (!_pedometer) {
        _pedometer = [[CMPedometer alloc]init];
    }
    return _pedometer;
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

#pragma mark - 初始化背景
- (void)setupMainUI {
    
    
    UIImage *image = [UIImage imageNamed:@"timg-2.jpeg"];
//    self.view.layer.contents = (id)image.CGImage;
    UIImageView * topBg = [[UIImageView alloc] init];
    [self.view addSubview:topBg];
    topBg.image = image;
    topBg.contentMode = UIViewContentModeScaleAspectFill;
    topBg.clipsToBounds = YES;
    [topBg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    
    
    
    _timeView = [[UIView alloc] init];
    [self.view addSubview:_timeView];
    
    [_timeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(SafeAreaTopHeight + 20);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.equalTo(self.timeView.mas_width);
    }];
    
    _timeView.backgroundColor = UIColor.clearColor;
    
    
    

    
    //  设置追踪视图
    _trackView = [[CountDownView alloc] init];
    _trackView.flag = @"track";
    _trackView.backgroundColor = UIColor.clearColor;
    [self.timeView addSubview:_trackView];
    
    _processView = [[CountDownView alloc] init];
    _processView.flag = @"process";
    _processView.time = 1000;
    _processView.backgroundColor = UIColor.clearColor;
    [self.timeView addSubview:_processView];
    
    [_trackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.timeView);
        make.left.equalTo(self.timeView).offset(60);
        make.right.equalTo(self.timeView).offset(-60);
        make.height.equalTo(self.trackView.mas_width);
    }];
    
    [_processView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.timeView);
        make.left.equalTo(self.timeView).offset(60);
        make.right.equalTo(self.timeView).offset(-60);
        make.height.equalTo(self.processView.mas_width);
    }];
    
    _showTimeLabel = [[UILabel alloc] init];
    [self.timeView addSubview:_showTimeLabel];
    
    _showTimeLabel.text = @"0000";
    _showTimeLabel.font = [UIFont systemFontOfSize:45.0f weight:UIFontWeightRegular];
    _showTimeLabel.textColor = UIColor.whiteColor;
    _showTimeLabel.textAlignment = NSTextAlignmentCenter;
    [self.showTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.trackView);
        make.top.equalTo(self.trackView).offset((WIN_WIDTH - 120)/2.0f - 20);
        make.height.mas_equalTo(@40);
    }];
    
    _kmTips = [[UILabel alloc] init];
    [self.timeView addSubview:_kmTips];
    _kmTips.text = @"今日步数";
    _kmTips.textColor = UIColor.whiteColor;
    _kmTips.font = [UIFont systemFontOfSize:13.0f];
    [_kmTips mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.showTimeLabel);
        make.bottom.equalTo(self.showTimeLabel.mas_top).offset(-15);
    }];
    
    //  目标
    _preValue = [[UILabel alloc] init];
    [self.timeView addSubview:_preValue];
    
    _preValue.text = @"目标1000步";
    _preValue.textColor = UIColor.whiteColor;
    [_preValue mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.showTimeLabel.mas_bottom).offset(20);
        make.height.mas_equalTo(@25);
        make.centerX.equalTo(self.showTimeLabel);
    }];

    
    
    
    
    UIView *yourGradientView = [[UIView alloc] initWithFrame:self.view.bounds];
    
    // 渐变图层
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = yourGradientView.bounds;
    
    // 设置颜色
    gradientLayer.colors = @[(id)[[UIColor clearColor] colorWithAlphaComponent:0.0f].CGColor,
                             (id)[[UIColor whiteColor] colorWithAlphaComponent:1.0f].CGColor];
    gradientLayer.locations = @[[NSNumber numberWithFloat:0.6f],
                                [NSNumber numberWithFloat:1.0f]];
    
    // 添加渐变图层
    [yourGradientView.layer addSublayer:gradientLayer];
    [self.view addSubview:yourGradientView];
    // 开始动画效果
    GCDTimer * timer = [[GCDTimer alloc] initInQueue:[GCDQueue mainQueue]];
    [timer event:^{
        gradientLayer.locations = @[[NSNumber numberWithFloat:arc4random()%100/100.f],
                                    [NSNumber numberWithFloat:1.0f]];

        gradientLayer.colors = @[(id)[[UIColor clearColor] colorWithAlphaComponent:0.0f].CGColor,
                                 (id)[[UIColor colorWithRed:arc4random()%255/255.f
                                                      green:arc4random()%255/255.f
                                                       blue:arc4random()%255/255.f
                                                      alpha:1.0] colorWithAlphaComponent:1.0f].CGColor];
    } timeInterval:NSEC_PER_SEC];
    
    [timer start];
    
    
    
    _startBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:_startBtn];

    [_startBtn setBackgroundColor: [UIColor jk_gradientFromColor:JYColorFromHex(0x41adf6) toColor:JYColorFromHex(0x1e53d8) withHeight:40 width:WIN_WIDTH]];

    [_startBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [_startBtn setTitleColor:UIColor.whiteColor forState:UIControlStateSelected];
    
    
    
    
    [_startBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-80 - SafeAreaBottomHeight);
        make.height.mas_equalTo(@40);
        make.left.equalTo(self.view).offset(30);
        make.right.equalTo(self.view).offset(-30);
        make.centerX.equalTo(self.view);
    }];
    _startBtn.layer.cornerRadius = 2;
    //  阴影
    _startBtn.layer.shadowOffset =  CGSizeMake(1, 1);
    _startBtn.layer.shadowOpacity = 0.5;
    _startBtn.layer.shadowColor =  JYColorFromHex(0x41adf6).CGColor;
    
    [_startBtn setTitle:@"开始运动" forState:UIControlStateNormal];
    [_startBtn setTitle:@"结束运动" forState:UIControlStateSelected];
    
    _centerView = [[UIView alloc] init];
    [self.view addSubview:_centerView];

    [_centerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.view);
        make.centerX.equalTo(self.view);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.mas_equalTo(@60);
    }];
    
    UILabel * tipssss = [[UILabel alloc] init];
    tipssss.text = @"总有一天，你会感谢坚持运动的自己";
    tipssss.textColor = UIColor.whiteColor;
    tipssss.font = [UIFont systemFontOfSize:13.0f];
    
     [self.view addSubview:tipssss];
    
    [tipssss mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.startBtn.mas_top).offset(-15);
        make.centerX.equalTo(self.view);
    }];
    
//    _totalKm = [[UIView alloc] init];
//    [self.centerView addSubview:_totalKm];
//
//    _totalKLL = [[UIView alloc] init];
//    [self.centerView addSubview:_totalKLL];
//
//    _totalPre = [[UIView alloc] init];
//    [self.centerView addSubview:_totalPre];
//
//    [self makeEqualWidthViews:@[self.totalKm, self.totalKLL, self.totalPre] inView:self.centerView LRpadding:0 viewPadding:0];
//
//    _kmValue = [[UILabel alloc] init];
//    _kmValue.text = @"0.00km";
//    _kmValue.font = [UIFont systemFontOfSize:20.0 weight:UIFontWeightSemibold];
//    _kmValue.textColor = UIColor.whiteColor;
//    _kmValue.textAlignment = NSTextAlignmentCenter;
//    [self.totalKm addSubview:_kmValue];
//
//    _kmTips = [[UILabel alloc] init];
//    _kmTips.text = @"公里";
//    _kmTips.font = [UIFont systemFontOfSize:14.0 weight:UIFontWeightRegular];
//    _kmTips.textColor = UIColor.whiteColor;
//    _kmTips.textAlignment = NSTextAlignmentCenter;
//    [self.totalKm addSubview:_kmTips];
//
//    _kllValue = [[UILabel alloc] init];
//    _kllValue.text = @"0cal";
//    _kllValue.font = [UIFont systemFontOfSize:20.0 weight:UIFontWeightSemibold];
//    _kllValue.textColor = UIColor.whiteColor;
//    _kllValue.textAlignment = NSTextAlignmentCenter;
//    [self.totalKLL addSubview:_kllValue];
//
//    _kllTips = [[UILabel alloc] init];
//    _kllTips.text = @"卡路里(参考值)";
//    _kllTips.font = [UIFont systemFontOfSize:14.0 weight:UIFontWeightRegular];
//    _kllTips.textColor = UIColor.whiteColor;
//    _kllTips.textAlignment = NSTextAlignmentCenter;
//    [self.totalKLL addSubview:_kllTips];
//
//    _preValue = [[UILabel alloc] init];
//    _preValue.text = @"0%";
//    _preValue.font = [UIFont systemFontOfSize:20.0 weight:UIFontWeightSemibold];
//    _preValue.textColor = UIColor.whiteColor;
//    _preValue.textAlignment = NSTextAlignmentCenter;
//    [self.totalPre addSubview:_preValue];
//
//    _preTips = [[UILabel alloc] init];
//    _preTips.text = @"今日目标";
//    _preTips.font = [UIFont systemFontOfSize:14.0 weight:UIFontWeightRegular];
//    _preTips.textColor = UIColor.whiteColor;
//    _preTips.textAlignment = NSTextAlignmentCenter;
//    [self.totalPre addSubview:_preTips];
//
//    //  布局
//    [_kmValue mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.totalKm);
//        make.left.equalTo(self.totalKm);
//        make.right.equalTo(self.totalKm);
//        make.height.mas_equalTo(@30);
//    }];
//
//    [_kmTips mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.kmValue.mas_bottom);
//        make.left.equalTo(self.totalKm);
//        make.right.equalTo(self.totalKm);
//        make.bottom.equalTo(self.totalKm);
//    }];
//
//    [_kllValue mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.totalKLL);
//        make.left.equalTo(self.totalKLL);
//        make.right.equalTo(self.totalKLL);
//        make.height.mas_equalTo(@30);
//    }];
//
//    [_kllTips mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.kllValue.mas_bottom);
//        make.left.equalTo(self.totalKLL);
//        make.right.equalTo(self.totalKLL);
//        make.bottom.equalTo(self.totalKLL);
//    }];
//
//    [_preValue mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.totalPre);
//        make.left.equalTo(self.totalPre);
//        make.right.equalTo(self.totalPre);
//        make.height.mas_equalTo(@30);
//    }];
//
//    [_preTips mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.preValue.mas_bottom);
//        make.left.equalTo(self.totalPre);
//        make.right.equalTo(self.totalPre);
//        make.bottom.equalTo(self.totalPre);
//    }];
    
//    _handleView = [[UIView alloc] init];
//    [self.view addSubview:_handleView];
//
//    [_handleView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.centerView.mas_bottom).offset(50);
//        make.left.equalTo(self.view);
//        make.right.equalTo(self.view);
//        make.height.mas_equalTo(@95);
//    }];
//    
//    _historyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [_historyBtn setImage:[UIImage imageNamed:@"btn_ history"] forState:UIControlStateNormal];
//    [self.handleView addSubview:_historyBtn];
//    _historyBtn.contentMode = UIViewContentModeScaleAspectFit;
//    
//
//    _setPlanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [_setPlanBtn setImage:[UIImage imageNamed:@"btn_install"] forState:UIControlStateNormal];
//    [self.handleView addSubview:_setPlanBtn];
//    _setPlanBtn.contentMode = UIViewContentModeScaleAspectFit;
//    
//    [self makeEqualWidthViews:@[self.historyBtn, self.setPlanBtn] inView:self.handleView LRpadding:30 viewPadding:15];
}

//  中间视图加载
- (JYCircleProgress *)circleProgress{
    if (!_circleProgress) {
        CGRect frame = CGRectMake(WIN_WIDTH/4-10, WIN_WIDTH/4-10, WIN_WIDTH/2+20, WIN_WIDTH/2+20);
        _circleProgress = [[JYCircleProgress alloc]initWithFrame:frame
                                                   pathBackColor:JYColorFromHex(0x81e3ee)
                                                   pathFillColor:JYColorFromHex(0xc8fec3)
                                                      startAngle:135
                                                     strokeWidth:10];
        
        _circleProgress.reduceAngle = 90;
        _circleProgress.progressLabel.font = [UIFont systemFontOfSize:45];
        _circleProgress.progressLabel.textColor = [UIColor whiteColor];
        _circleProgress.pointImage.image = [UIImage imageNamed:@"circle_point"];

    }
    return _circleProgress;
}


#pragma mark - 等宽登高设置
-(void)makeEqualWidthViews:(NSArray *)views inView:(UIView *)containerView LRpadding:(CGFloat)LRpadding viewPadding :(CGFloat)viewPadding
{
    UIView *lastView;
    for (UIView *view in views) {
        [containerView addSubview:view];
        if (lastView) {
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(containerView).offset(0);
                make.bottom.equalTo(containerView).offset(0);
                make.left.equalTo(lastView.mas_right).offset(viewPadding);
                make.width.equalTo(lastView);
            }];
        }else
        {
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(containerView).offset(LRpadding);
                make.top.equalTo(containerView).offset(0);
                make.bottom.equalTo(containerView).offset(0);
            }];
        }
        lastView=view;
    }
    [lastView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(containerView).offset(-LRpadding);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
